package com.sa.token.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sa.token.constant.Constants;
import com.sa.token.dto.request.user.LoginRequest;
import com.sa.token.dto.response.user.TokenResponse;
import com.sa.token.entity.SysUserEntity;
import com.sa.token.handler.LoginLog;
import com.sa.token.message.Result;
import com.sa.token.message.StandardResponse;
import com.sa.token.service.LoginService;
import com.sa.token.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

import static com.sa.token.utils.Md5Util.MD5Encode;

/**
 * @desc:登录注册实现
 * @author: xhs
 * @date: 2021/8/19 13:51
 * @version: JDK 1.8
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SysUserService userService;
    @Autowired
    private LoginLog loginLog;

    /**
     * 注册
     *
     * @param loginRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public StandardResponse<Object> register(LoginRequest loginRequest) {
        SysUserEntity userEntity = userService.getBaseMapper()
                .selectOne(new QueryWrapper<SysUserEntity>().lambda()
                        .eq(SysUserEntity::getLoginId, loginRequest.getUsername()));
        // 1.验证账号是否被注册过
        if (userEntity != null) {
            return StandardResponse.build(Result.ACCOUNT_ALREADY_ERROR);
        } else {
            SysUserEntity entity = SysUserEntity.builder()
                    .loginId(loginRequest.getUsername())
                    .password(MD5Encode(loginRequest.getPassword()))
                    .build();
            userService.save(entity);
            return StandardResponse.build(Result.REGISTER_SUCCESS);
        }
    }

    /**
     * 登录
     *
     * @param loginRequest
     * @return
     */
    @Override
    public StandardResponse<Object> login(HttpServletRequest request, LoginRequest loginRequest) {
        SysUserEntity userEntity = userService.getOne(new QueryWrapper<SysUserEntity>().lambda()
                .eq(SysUserEntity::getLoginId, loginRequest.getUsername())
                .eq(SysUserEntity::getDelFlg, 0));
        if (userEntity == null) {
            // 异步记录登录日志
            loginLog.loginLog(request,loginRequest.getUsername(), Constants.ERROR, Constants.LOGIN_ERROR);
            return StandardResponse.build(Result.ACCOUNT_PASSWORD_ERROR);
        }
        if (userEntity.getPassword().equals(MD5Encode(loginRequest.getPassword()))) {
            // 登录
            StpUtil.login(userEntity.getLoginId());
            // 异步记录登录日志
            loginLog.loginLog(request,StpUtil.getLoginId().toString(), Constants.SUCCESS,Constants.LOGIN_SUCCESS);
            // 获取token信息
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            // 返回token
            TokenResponse tokenResponse = TokenResponse.builder()
                    .tokenName(tokenInfo.getTokenName())
                    .tokenValue(tokenInfo.getTokenValue())
                    .build();
            return StandardResponse.build(Result.SUCCESS, tokenResponse);
        } else {
            // 异步记录登录日志
            loginLog.loginLog(request,loginRequest.getUsername(), Constants.ERROR,Constants.LOGIN_ERROR);
            return StandardResponse.build(Result.ACCOUNT_PASSWORD_ERROR);
        }
    }

    /**
     * 登出
     *
     * @return
     */
    @Override
    public StandardResponse<Object> logout() {
        StpUtil.logout();
        return StandardResponse.build(Result.SUCCESS);
    }
}
